<template>
  <div class="login-container">
    <div class="login-icon">
      <img src="../assets/icons/login.png" alt="" />
    </div>
    <div class="login-form-wrapper">
      <form @submit.prevent="handleLogin" class="login-form">
        <div class="input-container">
          <input
            type="text"
            id="account"
            placeholder=" "
            v-model="form.account"
          />
          <label for="account" class="label">账号</label>
          <div class="underline"></div>
        </div>
        <div class="input-container">
          <input
            type="text"
            id="password"
            placeholder=" "
            v-model="form.password"
          />
          <label for="password" class="label">密码</label>
          <div class="underline"></div>
        </div>

        <button type="submit" class="login-button" :disabled="loading">
          {{ loading ? "登录中..." : "登录" }}
        </button>

        <div class="register-link">
          还没有账号？<router-link to="/register">立即注册</router-link>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { useRouter } from "vue-router";
import { useUserStore } from "../store/user";
import { useWeatherStore } from "../store/weather";
import axios from "../utils/axios";
import { showToast } from "vant";

const router = useRouter();
const userStore = useUserStore();
const weatherStore = useWeatherStore();

const form = ref({
  account: "",
  password: "",
});

const loading = ref(false);

// 表单验证
function validateForm() {
  let isValid = true;

  // 验证账号
  if (!form.value.account.trim()) {
    showToast({ message: "账号不能为空", position: "bottom" });
    isValid = false;
  } else {
    const accountRegex = /^[0-9]{8,12}$/;
    if (!accountRegex.test(form.value.account)) {
      showToast({
        message: "账号只能包含数字，长度8-12位",
        position: "bottom",
      });
      isValid = false;
    }
  }

  // 验证密码
  if (!form.value.password) {
    showToast({ message: "密码不能为空", position: "bottom" });
    isValid = false;
  } else {
    const passwordRegex = /^[a-zA-Z0-9\W_]{8,18}$/;
    if (!passwordRegex.test(form.value.password)) {
      showToast({
        message: "密码只能包含字母、数字和特殊字符，长度8-18个字符",
        position: "bottom",
      });
      isValid = false;
    }
  }

  return isValid;
}

// 组件挂载时的初始化逻辑

const handleLogin = async () => {
  // 验证表单
  if (!validateForm()) {
    return;
  }

  loading.value = true;

  try {
    // 直接调用API而不是userStore.login，因为我们修改了登录参数
    const response = await axios.post("/users/login", {
      account: form.value.account,
      password: form.value.password,
    });
    console.log(response);

    const { token, user } = response;

    // 保存用户信息到store
    userStore.setUserInfo(user);

    // 保存token到localStorage
    localStorage.setItem("token", token);

    // 登录成功后立即获取天气数据，这样用户进入首页时就能看到天气信息
    await weatherStore.fetchWeatherData();

    // 登录成功后跳转到首页
    router.push("/");
  } catch (err) {
    // 提供更具体的错误提示
    if (err.response?.message) {
      showToast({
        message: err.response.message,
        position: "bottom",
      });
    } else if (err.response?.status === 401) {
      showToast({
        message: "账号或密码错误，请重新输入",
        position: "bottom",
      });
    } else {
      showToast({
        message: "登录失败，请稍后再试",
        position: "bottom",
      });
    }
  } finally {
    loading.value = false;
  }
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  background-color: #ffffff;
}

.login-icon {
  margin: 0 auto;
  margin-bottom: 30px;
  padding-top: 30px;
  width: 80%;
  background-color: #ffffff;
}

.login-form-wrapper {
  padding: 40px;
  width: 100%;
  max-width: 420px;
  box-sizing: border-box;
  background-color: #ffffff;
}

.form-group {
  margin-bottom: 20px;
  position: relative;
}

.form-group input {
  width: 100%;
  padding: 12px 16px;
  border: none;
  border-bottom: 1px solid #d9dde1;
  font-size: 14px;
  box-sizing: border-box;
}

.form-group input:focus {
  outline: none;
}

.form-group input:disabled {
  cursor: not-allowed;
}

.form-group input.error {
  border-color: #f5222d;
}

/* 错误提示样式 */
.error-hint {
  color: #f5222d;
  font-size: 12px;
  margin-top: 4px;
  line-height: 1.4;
}

.forgot-password {
  font-size: 14px;
  color: #1677ff;
  text-decoration: none;
}

.forgot-password:hover {
  text-decoration: underline;
}

.login-button {
  width: 100%;
  background-color: #000000;
  color: white;
  border: none;
  border-radius: 10px;
  padding: 18px 24px;
  font-size: 20px;
  font-weight: 500;
  cursor: pointer;
}

.register-link {
  text-align: center;
  margin-top: 20px;
  font-size: 14px;
  color: #4e5969;
}

.register-link a {
  color: #000000;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}

.error-message {
  background-color: #fff1f0;
  border: 1px solid #ffccc7;
  border-radius: 6px;
  padding: 12px 16px;
  margin-top: 20px;
  color: #f5222d;
  font-size: 14px;
}

@media (max-width: 480px) {
  .login-form-wrapper {
    padding: 24px;
  }

  .logo {
    font-size: 40px;
  }

  .logo-section h2 {
    font-size: 20px;
  }

  .remember-forgot {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
}
.agreement {
  display: flex;
  align-items: flex-start;
  gap: 8px;
}

.agreement input[type="checkbox"] {
  margin-top: 2px;
  width: auto;
}

.agreement label {
  font-size: 14px;
  color: #4e5969;
  cursor: pointer;
  margin-bottom: 0;
}

.agreement-link {
  color: #1677ff;
  text-decoration: none;
}

.agreement-link:hover {
  text-decoration: underline;
}
/* From Uiverse.io by Satwinder04 */
.input-container {
  position: relative;
  margin-bottom: 40px;
}

.input-container input[type="text"] {
  width: 100%;
  border: none;
  border-bottom: 1px solid #d9dde1;
  background-color: transparent;
  outline: none;
  padding: 12px 16px;
}

.input-container .label {
  position: absolute;
  top: 0;
  left: 16px;
  color: #6a6a6a;
  transition: all 0.3s ease;
  pointer-events: none;
}

.input-container input[type="text"]:focus ~ .label,
.input-container input[type="text"]:not(:placeholder-shown) ~ .label {
  top: -20px;
  font-size: 16px;
  color: #000000;
}

.input-container .underline {
  position: absolute;
  bottom: 0;
  left: 0;
  height: 1px;
  width: 100%;
  background-color: #000000;
  transform: scaleX(0);
  transition: all 0.3s ease;
}

.input-container input[type="text"]:focus ~ .underline,
.input-container input[type="text"]:not(:placeholder-shown) ~ .underline {
  transform: scaleX(1);
}
</style>
